#include "QSPrecompiledHeaders.h"
#include "QSEventSystemImpl.h"

#include <boost/foreach.hpp>

using namespace QS;

void EventSystemImpl::initialize(){}
void EventSystemImpl::shutdown(){}

void EventSystemImpl::update()
{
	std::swap(mFrontQueue, mBackQueue);
	while(!mBackQueue.empty())
		dispatchEvent(mBackQueue);
}

void EventSystemImpl::queueEvent(const Event& e)
{
	mFrontQueue.push(e);
}

void EventSystemImpl::postEvent(const Event& e)
{
	queueEvent(e);
	dispatchEvent(mFrontQueue);
}

void EventSystemImpl::addEventListener(EventListener* l)
{
	EventListenerList::const_iterator iter = find(mListeners.begin(), mListeners.end(), l);	
	if (iter == mListeners.end())
		mListeners.push_back(l);
}

void EventSystemImpl::removeEventListener(EventListener* l)
{
	EventListenerList::iterator iter = find(mListeners.begin(), mListeners.end(), l);	
	if (iter != mListeners.end())
		mListeners.erase(iter);
}

void EventSystemImpl::dispatchEvent(EventQueue& q)
{
	Event e = q.front();
	q.pop();

	BOOST_FOREACH(EventListener* lstnr, mListeners)
	{
		lstnr->processEvent(e);
	}

	boost::checked_delete(e.getArgs());
}